﻿<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="1" />

    <title>文件管理器</title>
    <script src="jquery-1.11.2.js"></script>
    <script src="jquery.ajaxfileupload.js"></script>

    <style type="text/css">
        span {
            cursor: pointer;
            color: blue;
        }
    </style>

    <script type="text/javascript">
        var apiConstants = {
            API_STATUS_SUCCES: 1,//成功
            API_STATUS_FAIL: 2,//失败
            API_STATUS_EXCEPTION: 3,//异常
            API_STATUS_AUTH_FAIL: 4,//认证失败
            AJAX_REQ_ERROR: 5,//ajax请求错误
        };

        var baseUrl = window.document.location.href + "api/v1/fileService/";
        var _path = "";
        var tdList = null;
        var tbodyList = null;
        var tbUploadEle = null;


        //获取当前本地时间的时间戳
        function getTimestamp() {
            var dateTime = new Date();
            return dateTime.getTime() - dateTime.getTimezoneOffset() * 60 * 1000;
        }


        function showErr(err) {
            alert(err);
        }

        function showErrRet(err, p1) {
            if (err.status == 200) {
                //浏览器bug,内容复杂的json解析会失败,提示说解析错误.不鸟它
                showErr("浏览器内容复杂的json解析会失败");
            }
            else {
                showErr(err.statusText);
            }
        }

        function toShowyyyyMMddHHmmss(date) {
            if (!(date instanceof Date)) {
                throw "date,且不能为空或未定义";
            }

            var year = date.getFullYear();
            var month = date.getMonth() + 1;//月取值0-11，所以+1
            var days = date.getDate();
            var h = date.getHours();
            var m = date.getMinutes();
            var s = date.getSeconds();
            return year + "-" + month + "-" + days + " " + h + ":" + m + ":" + s;
        }

        function setTBodyInnerHTML(tbody, html) {
            var div = document.createElement('div');
            div.innerHTML = '<table>' + html + '</table>';
            while (tbody.firstChild) {
                tbody.removeChild(tbody.firstChild);
            }
            tbody.appendChild(div.firstChild.firstChild);
        }

        function refreshNav() {
            var arr = _path.split('/')
            var tmpPath = "";
            var html = "";
            for (var i = 0; i < arr.length; i++) {
                if (i == 0) {
                    html += '<span data-path="" onclick="chioceDir(this)">..</span>';
                }
                else {
                    tmpPath += "/" + arr[i];
                    html += '/<span data-path="' + tmpPath + '" onclick="chioceDir(this)">' + decodeURIComponent(arr[i]) + '</span>';
                }
            }

            var divNavEle = document.getElementById("divNav");
            divNavEle.innerHTML = html;
        }

        function showList(ret) {
            var list = JSON.parse(ret.data);
            var html = '';
            var dir = null;
            for (var j = 0; j < list.length; j++) {
                var item = list[j];
                if (item.length > 0) {
                    if (dir == null) {
                        var arr = _path.split('/');
                        var flag = true;
                        for (var i = 0; i < arr.length; i++) {
                            if (arr[i] == '') {
                                continue;
                            }

                            if (flag) {
                                flag = false;
                            }
                            else {
                                if (dir == null) {
                                    dir = arr[i];
                                }
                                else {
                                    dir += '/';
                                    dir += arr[i];
                                }
                            }
                        }

                        if (dir == null) {
                            dir = '';
                        }
                    }


                    html += '<tr data-type="1">\
                                <td><input type="checkbox" /></td >\
                                <td><a href="'+ dir + '/' + encodeURIComponent(item.name) + '" download>' + item.name + '</a></td>\
                                <td>'+ item.createTime + '</td>\
                                <td>'+ item.lastModifyTime + '</td>\
                                <td>'+ item.length / 1000 + '</td>\
                            </tr>';
                }
                else {
                    html += '<tr data-type="0">\
                                <td><input type="checkbox" /></td >\
                                <td> <span onclick="switchDir(\''+ encodeURIComponent(item.name) + '\')">' + item.name + '</span></td>\
                                <td>'+ item.createTime + '</td>\
                                <td>'+ item.lastModifyTime + '</td>\
                                <td>目录('+ item.count + ')</td>\
                            </tr>';
                }
            }


            tdList.innerHTML = '<table>' + ' <thead>\
                                                     <tr>\
                                                         <td style="width:50px">选中</td>\
                                                         <td style="width:400px">名称</td>\
                                                         <td style="width:200px">创建时间</td>\
                                                         <td style="width:200px">最后修改时间</td>\
                                                         <td style="width:200px">文件长度(K)/文件数</td>\
                                                     </tr>\
                                                 </thead><tbody id="tbodyList">' + html + ' </tbody></table>';
            tbodyList = document.getElementById("tbodyList");
            //setTBodyInnerHTML(tbodyList, html);
        }


        function refreshList(path) {
            var url = null;
            if (path != null) {
                url = baseUrl + "getFileSystemInfos?path=" + path;
            }
            else {
                url = baseUrl + "getFileSystemInfos?path=";
            }

            $.ajax({
                type: "GET",
                url: url,
                async: true,
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                success: function (ret, status, p1) {
                    if (ret.status == apiConstants.API_STATUS_SUCCES) {
                        showList(ret);
                        refreshNav();
                    }
                    else {
                        showErr(ret.data);
                    }
                },
                error: showErrRet
            });
        }


        function checkAll() {
            for (var i = 0; i < tbodyList.children.length; i++) {
                tbodyList.children[i].children[0].children[0].checked = true;
            }
        }

        function unCheckAll() {
            for (var i = 0; i < tbodyList.children.length; i++) {
                tbodyList.children[i].children[0].children[0].checked = false;
            }
        }

        function unCheck() {
            for (var i = 0; i < tbodyList.children.length; i++) {
                tbodyList.children[i].children[0].children[0].checked = !tbodyList.children[i].children[0].children[0].checked;
            }
        }

        function onRefresh() {
            refreshList(_path);
        }

        function switchDir(dir) {
            _path = _path + '/' + dir;
            refreshList(_path);
        }

        function chioceDir(ele) {
            _path = ele.getAttribute("data-path");
            refreshList(_path);
        }



        //http-post 上传文件
        var uploadProBar = null;
        var _uploadFileList = [];
        var _uploading = false;
        var _uploadRow = null;

        function primitiveUploadFile() {
            if (_uploadFileList.length == 0) {
                _uploading = false;
                _uploadRow = null;
                return;
            }

            var item = _uploadFileList[0];
            _uploadFileList.splice(0, 1);//取出第一项后,将第一项从待上传列表中移除
            var rowId = item.id.toString();
            _uploadRow = document.getElementById(rowId);
            if (_uploadRow != null && _uploadRow != undefined) {
                _uploadRow.children[3].children[0].setAttribute("disabled", "disabled");
            }

            var url = baseUrl + "uploadFile?path=" + _path;
            $.ajaxFileUpload({
                url: url, //用于文件上传的服务器端请求地址
                secureuri: false, //一般设置为false
                fileElementId: 'txtUploadFile', //文件上传空间的id属性 <input type="file" id="file" name="file" />
                dataType: 'json', //返回值类型 一般设置为json
                xhr: function () {
                    var xhr = new XMLHttpRequest();
                    //使用XMLHttpRequest.upload监听上传过程，注册progress事件，打印回调函数中的event事件
                    xhr.upload.addEventListener('progress', function (e) {
                        //console.log(e);//progress { target: XMLHttpRequestUpload, isTrusted: true, lengthComputable: true, loaded: 761134475, total: 770732404, srcElement: XMLHttpRequestUpload, currentTarget: XMLHttpRequestUpload, eventPhase: 2, bubbles: false, cancelable: false, … }
                        //loaded代表上传了多少
                        //total代表总数为多少

                        //let progressRate = (e.loaded / e.total) * 100 + '%';
                        //通过设置进度条的宽度达到效果
                        //$('.progress > div').css('width', progressRate);

                        if (_uploadRow != null && _uploadRow != undefined) {
                            var numb = e.loaded / e.total * 100;
                            _uploadRow.children[2].innerText = numb.toFixed(2) + "%";
                            //uploadProBar.innerText = numb.toFixed(2) + "%";
                        }
                    })

                    return xhr;
                },
                success: function (data, status) {//服务器成功响应处理函数
                    if (ret.status == apiConstants.API_STATUS_SUCCES) {
                        if (_uploadRow != null && _uploadRow != undefined) {
                            //let id = parseInt(_uploadRow.id);
                            //let removeIndex = -1;
                            //for (let i = 0; i < _uploadFileList.length; i++) {
                            //    if (_uploadFileList[i].id == id) {
                            //        removeIndex = i;
                            //        break;
                            //    }
                            //}
                            //if (removeIndex >= 0) {
                            //    _uploadFileList.splice(removeIndex, 1);
                            //}
                            _uploadRow.remove();
                        }
                        _uploadRow = null;

                        refreshList(_path);
                        primitiveUploadFile();
                    }
                    else {
                        if (_uploadRow != null && _uploadRow != undefined) {
                            _uploadRow.children[2].innerText = "失败";
                        }

                        showErr(ret.data);
                    }
                },
                error: function (err, p1) {//服务器响应失败处理函数
                    if (_uploadRow != null && _uploadRow != undefined) {
                        _uploadRow.children[2].innerText = "失败";
                    }
                    showErrRet(err, p1);
                }
            });

        }


        function onCancelUpload(id) {
            var rowId = id.toString();
            var rowEle = document.getElementById(rowId);
            if (rowEle != null && rowEle != undefined) {
                rowEle.remove();
            }
        }

        function eleChanged(sender) {
            var url = baseUrl + "uploadFile?path=" + _path;
            //$.ajaxFileUpload({
            $.fn.AjaxFileUpload({
                url: url, //用于文件上传的服务器端请求地址
                secureuri: false, //一般设置为false
                fileElementId: 'txtUploadFile', //文件上传空间的id属性 <input type="file" id="file" name="file" />
                dataType: 'json', //返回值类型 一般设置为json
                xhr: function () {
                    var xhr = new XMLHttpRequest();
                    //使用XMLHttpRequest.upload监听上传过程，注册progress事件，打印回调函数中的event事件
                    xhr.upload.addEventListener('progress', function (e) {
                        //console.log(e);//progress { target: XMLHttpRequestUpload, isTrusted: true, lengthComputable: true, loaded: 761134475, total: 770732404, srcElement: XMLHttpRequestUpload, currentTarget: XMLHttpRequestUpload, eventPhase: 2, bubbles: false, cancelable: false, … }
                        //loaded代表上传了多少
                        //total代表总数为多少

                        //let progressRate = (e.loaded / e.total) * 100 + '%';
                        //通过设置进度条的宽度达到效果
                        //$('.progress > div').css('width', progressRate);

                        if (_uploadRow != null && _uploadRow != undefined) {
                            var numb = e.loaded / e.total * 100;
                            _uploadRow.children[2].innerText = numb.toFixed(2) + "%";
                            //uploadProBar.innerText = numb.toFixed(2) + "%";
                        }
                    })

                    return xhr;
                },
                success: function (data, status) {//服务器成功响应处理函数
                    if (ret.status == apiConstants.API_STATUS_SUCCES) {
                        //if (_uploadRow != null && _uploadRow != undefined) {
                        //    //let id = parseInt(_uploadRow.id);
                        //    //let removeIndex = -1;
                        //    //for (let i = 0; i < _uploadFileList.length; i++) {
                        //    //    if (_uploadFileList[i].id == id) {
                        //    //        removeIndex = i;
                        //    //        break;
                        //    //    }
                        //    //}
                        //    //if (removeIndex >= 0) {
                        //    //    _uploadFileList.splice(removeIndex, 1);
                        //    //}
                        //    _uploadRow.remove();
                        //}
                        //_uploadRow = null;

                        refreshList(_path);
                        //primitiveUploadFile();
                    }
                    else {
                        if (_uploadRow != null && _uploadRow != undefined) {
                            _uploadRow.children[2].innerText = "失败";
                        }

                        showErr(ret.data);
                    }
                },
                error: function (err, p1) {//服务器响应失败处理函数
                    if (_uploadRow != null && _uploadRow != undefined) {
                        _uploadRow.children[2].innerText = "失败";
                    }
                    showErrRet(err, p1);
                }
            });

            //var rowEle = null;
            //var ts = getTimestamp();
            //var index = 0;
            //$('input[type=file]').each(function () {
            //    var length = this.files.length;
            //});

            //for (var i = 0; i < sender.files.length; i++) {
            //    var file = sender.files[i];
            //    var item = {};
            //    item.id = ts + index++;
            //    item.name = file.name;
            //    item.file = file;
            //    _uploadFileList.push(item);

            //    rowEle = tbUploadEle.insertRow(tbUploadEle.children.length);
            //    rowEle.id = item.id;
            //    rowEle.innerHTML = '<td>' + item.name + '</td ><td>' + file.size / 1024 + '</td><td>0</td><td><button onclick="onCancelUpload(' + item.id + ')">取消</button>';
            //}

            //if (!_uploading) {
            //    _uploading = true;
            //    primitiveUploadFile();
            //}
        }

        function onUploadFile() {
            alert("上传未实现");
            return;

            var ele = document.getElementById("txtUploadFile");
            ele.value = "";//清空前一次选择的文件
            ele.click();
        }

        function onCreateDir() {
            var dir = $("#newDir").val().trim();
            if (dir == "") {
                showErr("目录不能为空");
                return;
            }

            var url = baseUrl + "createDirectory?path=" + _path + '/' + dir;
            $.ajax({
                type: "GET",
                url: url,
                async: true,
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                success: function (ret, status, p1) {
                    if (ret.status == apiConstants.API_STATUS_SUCCES) {
                        refreshList(_path);
                    }
                    else {
                        showErr(ret.data);
                    }
                },
                error: showErrRet
            });
        }

        function onBatchDelete() {
            var arr = new Array();
            for (var i = 0; i < tbodyList.children.length; i++) {
                var trEle = tbodyList.children[i];
                if (trEle.children[0].children[0].checked == true) {
                    var item = {};
                    item.name = trEle.children[1].children[0].innerHTML;
                    if (trEle.getAttribute("data-type") == "1") {//文件
                        item.length = 1;
                    }
                    else {//目录
                        item.length = 0;
                    }
                    arr.push(item);
                }
            }

            if (arr.length == 0) {
                return;
            }

            var data = {};
            data.list = arr;
            data.path = decodeURIComponent(_path);
            var url = baseUrl + "delete";
            var json = JSON.stringify(data);

            $.ajax({
                type: "POST",
                url: url,
                data: json,
                async: true,
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                success: function (ret, status, p1) {
                    if (ret.status == apiConstants.API_STATUS_SUCCES) {
                        refreshList(_path);
                    }
                    else {
                        showErr(ret.data);
                    }
                },
                error: showErrRet
            });
        }



        function onBatchDownload() {
            for (var i = 0; i < tbodyList.children.length; i++) {
                var trEle = tbodyList.children[i];
                if (trEle.children[0].children[0].checked == true) {
                    if (trEle.getAttribute("data-type") == "0") {
                        //目录
                        continue;
                    }

                    //文件
                    trEle.children[1].children[0].click();
                }
            }
        }


        function onLoad() {
            //if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
            //    baseUrl = window.document.location.href + "api/v1/fileService/";
            //}
            //else {
            //    baseUrl = window.document.location.origin + "/api/v1/fileService/";
            //}

            tdList = document.getElementById("tdList");
            tbUploadEle = document.getElementById("tbUpload");
            uploadProBar = document.getElementById('bar');

            refreshList(_path);
        }
    </script>
</head>

<body onload="onLoad();">
    <table>
        <tr style="height:30px;">
            <td colspan="2">
                <div id="divNav" style="height: 30px; border: solid 1px gray; margin: 5px;">
                    <!--<span>..</span>/<span>aa</span>/<span>bb</span>/<span>c</span>-->
                </div>
            </td>
        </tr>
        <tr style="height: calc(100% - 70px);">
            <td id="tdList">
                <style>
                    tr {
                        height: 30px;
                    }
                </style>

                <!--<table>
                    <thead>
                        <tr>
                            <td style="width:50px">选中</td>
                            <td style="width:400px">名称</td>
                            <td style="width:200px">创建时间</td>
                            <td style="width:200px">最后修改时间</td>
                            <td style="width:200px">文件长度(K)/文件数</td>
                        </tr>
                    </thead>
                    <tbody id="tbodyList">
                        <tr>
                            <td><input type="checkbox" /></td>
                            <td>
                                <a href="index2.html">张三李四王麻子</a>
                            </td>
                            <td>2024-10-10 13:29:38</td>
                            <td>2024-10-12 21:09:12</td>
                            <td>172.7</td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" /></td>
                            <td>
                                <a href="index2.html">张三李四王麻子</a>
                            </td>
                            <td>2024-10-10 13:29:38</td>
                            <td>2024-10-12 21:09:12</td>
                            <td>172.7</td>
                        </tr>
                    </tbody>
                </table>-->
            </td>
            <td style="width:30%;">
                <table id="tbUpload">
                    <thead>
                        <tr>
                            <td style="width:400px">名称</td>
                            <td style="width:200px">大小K</td>
                            <td style="width:200px">进度%</td>
                            <td style="width:200px">操作</td>
                        </tr>
                    </thead>

                    <tbody>
                        <!--<tr id="qwe">
                            <td>
                                feiq.exe
                            </td>
                            <td>205</td>
                            <td>0</td>
                            <td><button onclick="onCreateDir(123)">取消</button></td>
                        </tr>
                        <tr id="qwe">
                            <td>
                                feiq.exe
                            </td>
                            <td>205</td>
                            <td>0</td>
                            <td><button onclick="onCreateDir(123)">取消</button></td>
                        </tr>
                        <tr id="qwe">
                            <td>
                                feiq.exe
                            </td>
                            <td>205</td>
                            <td>0</td>
                            <td><button onclick="onCreateDir(123)">取消</button></td>
                        </tr>-->
                    </tbody>
                </table>
            </td>
        </tr>
        <tr style="height:40px;">
            <td colspan="2">
                <div style="height: 40px; border: solid 1px gray; margin: 5px;">
                    <style type="text/css">
                        button {
                            margin: 2px;
                            vertical-align: central;
                            width: 110px;
                            height: 35px;
                        }
                    </style>

                    <button onclick="checkAll()" style="margin-left:10px">全选</button>
                    <button onclick="unCheckAll()" style="margin-left:10px">全不选</button>
                    <button onclick="unCheck()" style="margin-left:10px">反选</button>

                    <button onclick="onRefresh()" style="margin-left:10px">刷新</button>
                    <input title="文件" id="txtUploadFile" accept="*.*" type="file" multiple="multiple" style="display:none" onchange="eleChanged(this)">
                    <button onclick="onUploadFile()" style="margin-left:10px">上传</button>
                    <label style="margin-left:10px">目录名</label>
                    <button onclick="onBatchDelete()" style="margin-left:10px">删除</button>
                    <button onclick="onBatchDownload()" style="margin-left:10px">下载</button>
                    <input type="text" id="newDir" value="" style="height:30px" />
                    <button onclick="onCreateDir()">创建目录</button>
                </div>
            </td>
        </tr>
    </table>

</body>
</html>